﻿using Api.Application.Command.Menu;
using Api.DTO;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;

namespace Api.Application.Handler.Menu
{
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, ApiPaging<MenuDTO>>
    {
        private readonly IBase<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public GetMenuHandler(IBase<MenuModel> menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiPaging<MenuDTO>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<MenuDTO> result =new ApiPaging<MenuDTO>();
            var menu = menuRepo.GetAll().Where(x => x.IsDeleted == false);
            var menus= menuRepo.GetAll().Where(x => x.IsDeleted == false);
            var linq = from a in menu
                       join b in menus.DefaultIfEmpty()
                       on a.PId equals b.Id into ab
                       from b in ab.DefaultIfEmpty()
                       
                       select new MenuDTO()
                       {
                           PId = a.PId,
                           CrearName = a.CrearName,
                           CrearTime = a.CrearTime,
                           MenuName = a.MenuName,
                           UpdateName   = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           Url = a.Url,
                           Id = a.Id,
                           ParentName=b.MenuName,
                       };
            result.Msg = "菜单显示成功";
            result.Data=linq.OrderByDescending(x=>x.CrearTime).ToList();
            result.Code = ApiEnum.OK;
            return Task.FromResult(result); 
        }
    }
}
